import re

from qiniu import Auth, put_data, BucketManager

# access_key = "cOHVAF0aKxB8dAwdkxABxlFSCpiW0bhRQaw0lsQf"
# secret_key = "VvPBoqE_pH6RNdQvEZCAoOx2oVtgsinxVY9TwfZq"
# q = Auth(access_key,secret_key)


QINIU_DOMAIN = "http://qhsalvmhx.hn-bkt.clouddn.com"
access_key = "cOHVAF0aKxB8dAwdkxABxlFSCpiW0bhRQaw0lsQf"
secret_key = "VvPBoqE_pH6RNdQvEZCAoOx2oVtgsinxVY9TwfZq"

def upload_qiniu(filestorage,image_filename):


    # 构建鉴权对象
    q = Auth(access_key, secret_key)

    # 要上传的空间
    bucket_name = "photographs"

    # 设置 上传之后保存文件的名字
    filename = 'weitezh_' + image_filename

    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, filename, 3600)

    # put_file()
    ret, info = put_data(token, filename, filestorage.read())

    if info.status_code == 200:
        url = QINIU_DOMAIN + '/' +filename

        return url
    return None



def remove_qiniu(image_url):

    '''删除图片'''

    # http: // qhsalvmhx.hn - bkt.clouddn.com / weitezh__xjzx_0f755453 - dc84 - 31ec - acb0 - 4fde7f0b8da5.jpg
    try:
        ret = re.search(r'.*com/(.*)',image_url)

        # 要删除的文件名
        image_name = ret.group(1)

        print(image_url)
        print(image_name)

        # 初始化Auth状态
        q = Auth(access_key, secret_key)
        # 初始化BucketManager
        bucket = BucketManager(q)
        # 你要测试的空间， 并且这个key在你空间中存在
        bucket_name = 'photographs'


        # 删除bucket_name 中的文件 key
        ret, info = bucket.delete(bucket_name, image_name)
        print(info)
        assert ret == {}

        return True
    except Exception as e:
        print(e)
        return False